#!/usr/bin/env python

"""
Read samples from the USRP and write to file formatted as binary
outputs single precision complex float values or complex short values (interleaved 16 bit signed short integers).

"""

from gnuradio import gr, eng_notation
from gnuradio import audio
from gnuradio import usrp
from gnuradio.eng_option import eng_option
from optparse import OptionParser
import sys, os

class usrp2wav(gr.top_block):

    def __init__(self,filename, sample_time=10.0, gain=None):
        gr.top_block.__init__(self)

        DECIMATION = 32
        FREQUENCY = 0
        rx_subdev_spec = (0,0)
        
        self.filename = "DO_NOT_USE"
        # SET UP THE FLOW GRAPH
        self.u = usrp.source_c(decim_rate=DECIMATION)
    
        input_rate = self.u.adc_freq() / self.u.decim_rate()
        
        self.c2r = gr.complex_to_real() 
        self.head0 = gr.head(gr.sizeof_float, int(sample_time*input_rate))
        self.dst = gr.wavfile_sink(filename, 1, input_rate)
    
        self.connect(self.u, self.c2r, self.head0, self.dst)   

        if rx_subdev_spec is None:
            rx_subdev_spec = usrp.pick_rx_subdevice(self.u)
        self.u.set_mux(usrp.determine_rx_mux_value(self.u, rx_subdev_spec))
    
        # determine the daughterboard subdevice we're using
        self.subdev = usrp.selected_subdev(self.u, rx_subdev_spec)
        print "Using RX d'board %s" % (self.subdev.side_and_name(),)
        input_rate = self.u.adc_freq() / self.u.decim_rate()
        print "USB sample rate %s" % (eng_notation.num_to_str(input_rate))
    
        if gain is None:
            # if no gain was specified, use the mid-point in dB
            g = self.subdev.gain_range()
            gain = float(g[0]+g[1])/2
    
        self.subdev.set_gain(gain)
    
        r = self.u.tune(0, self.subdev, FREQUENCY)
        if not r:
            sys.stderr.write('Failed to set frequency\n')
            raise SystemExit, 1


if __name__ == '__main__':
    import time

    ITERATION_PERIOD = 20
    SAMPLE_TIME = 10
    N_ITERATIONS = sys.maxint
    
    try:
        i = 0
        while i<N_ITERATIONS:
            start_time = time.localtime()
            fname = "/data/" + time.strftime("%Y_%m_%d_%Hh%Mm%Ss.wav")
            
            #take the sample
            usrp2wav(fname,sample_time=SAMPLE_TIME).run()
            
            #compress the file
            os.system("bzip2 " + filename)

            duration = time.time()-time.mktime(start_time)
            print("Sample %s took %d seconds" % (fname,duration))
            self.stdout.flush()
            time_till_next_iter = ITERATION_PERIOD - duration
            if time_till_next_iter > 0.0:
                time.sleep(duration)
            i=i+1
            
    except KeyboardInterrupt:
        print("Sampling Interrupted by User")
